<template>
  <basic-dialog  :visible="show"
                 minWidth="1000px"
                 title="停机原因明细"
                 :isShowClose="true"
                 :isFullScreen="false"
                 class="add-edit-plant-plan-dialog"
                 @close="$emit('close')">
    <q-card-section class="flex" style="padding: 10px 0">
        <!-- 信息-->
        <div class="row flex padding-l-20" style="padding-top: 10px ">
          <div class="margin-b-10 w">车间:{{location.workshop}}</div>
          <div class="margin-b-10 w text-ellipsis">
            原因：{{location.reason}}
            <q-tooltip>{{location.reason}}</q-tooltip>
          </div>
          <div class="margin-b-10 w">停机时长:{{location.longTime}}分钟</div>
        </div>
        <div class="form-inline" style=" position: absolute; right: 0; margin-top:5px">
          <q-btn
            class="btn"
            outline
            @click="onExcel"
            :disable="!tableData.length"
            color="primary"
            label="导出Excel"
          />
        </div>

        <!-- 图表-->
        <q-table
          :data="tableData"
          :columns="columns"
          row-key="id"
          id="reportTableDialog"
          class="myTable scroll inherit"
          style="margin: 10px 20px; max-height: 350px; width: calc(100% - 40px)"
          :pagination.sync="pagination"
          :hide-bottom="!!tableData.length"
          :loading="isTableLoading"
          color="primary"
        ></q-table>
      </q-card-section>
      <!--  分页-->
      <!-- <pagination v-model="pagination.page"
                  :page-size="pagination.rowsPerPage"
                  :total="pagination.rowsNumber"
                  @changePageSize="onPageSizeChange"
                  @changePage="onPageChange"
      style="margin-bottom: 20px" />-->
  </basic-dialog>
</template>

<script>
// import Pagination from '../../../components/pagination/index'
import { getDailyReport } from '../../../boot/statistics/stop-reason'
import exportJs from './export'
import { mapGetters } from 'vuex'
import moment from 'moment'
// import _ from 'lodash'
export default {
  name: 'performance-detail',
  components: {
    // Pagination
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    rowData: Object,
    queryParams: Object,
    stopType: String
  },
  data () {
    return {
      // 表格头部数据
      tableColumns: [],
      // 表格内容
      tableData: [],
      // 表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      rowParams: {},
      queryData: {},
      causeStopType: '',
      // 显示车间的信息
      location: {
        workshop: '',
        reason: '',
        longTime: ''
      },
      // 表格正在加载
      isTableLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    columns () {
      const tableColumns = [
        { name: 'indexId', field: 'indexId', label: '序号', align: 'left' },
        {
          name: 'deviceName',
          field: 'deviceName',
          label: '设备名称',
          align: 'left'
        },
        {
          name: 'lineName',
          field: 'lineName',
          label: '所在位置',
          align: 'left'
        }
      ]
      return [...tableColumns, ...this.tableColumns]
    }
  },
  watch: {
    // 监听查询元素
    queryParams: {
      handler (newPro) {
        if (newPro) {
          this.queryData = newPro
        }
      },
      deep: true,
      immediate: true
    },
    // 监听行元素
    rowData: {
      handler (newPro) {
        if (newPro) {
          this.rowParams = newPro
        }
      },
      deep: true,
      immediate: true
    },
    // 监听原因类别
    stopType: {
      handler (newPro) {
        this.causeStopType = newPro
      },
      immediate: true,
      deep: true
    },
    // 监听是否打开
    show (newPro) {
      if (newPro) {
        this.getDailyReport()
      }
    }
  },
  methods: {
    /**
       * on 分页组件的每页条数发生改变
       * @param val 每页条数
       */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getDailyReport()
    },

    /**
       * on 分页组件的页码发生改变
       * @param val 页码
       */
    onPageChange: function (val) {
      this.pagination.page = val
      this.getDailyReport()
    },
    getDate (date) {
      return moment(date).format('YYYYMMDD')
    },
    //
    onExcel () {
      // let workbook = document.querySelector('#reportTableDialog')
      // // raw : true 将数字转化为字符串
      // let sheet = XLSX.utils.table_to_sheet(workbook, { raw: true })
      // try {
      //   exportJs.openDownloadDialog(exportJs.sheet2blob(sheet), '停机原因分析.xlsx')
      // } catch (error) {
      //   console.log(error)
      // }
      // console.log(this.queryData)
      const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语祯物联'
      const stopReason = `停机原因明细(${this.getDate(this.queryData.dateRange[0])}-${this.getDate(this.queryData.dateRange[1])})`
      const undesirableReason = `停机原因： ${this.location.reason}`
      const countTime = `停机时长： ${this.location.longTime}分钟`
      const tableHead = this.getExportTableHead()
      const tableData = []
      const position = `车间: ${this.location && this.location.workshop}`
      const excelName = `${this.getDate(this.queryData.dateRange[0])}-${this.getDate(this.queryData.dateRange[1])}-停机原因明细报表`
      const sheetName = `${this.getDate(this.queryData.dateRange[0])}-${this.getDate(this.queryData.dateRange[1])}-停机原因明细报表`
      this.tableData.forEach(v1 => {
        // 总计
        const v1KesArr = Object.keys(v1)
        const item = []
        tableHead.forEach((v2, index) => {
          if (v2 === '序号') {
            item.push(v1.indexId)
          } else if (v2 === '设备名称') {
            item.push(v1.deviceName)
          } else if (v2 === '所在位置') {
            item.push(v1.lineName)
          } else {
            let findI = v2
            if (this.queryParams.dateType === 'month') {
              findI = v2.split('-').join('')
            } else if (this.queryParams.dateType === 'week') {
              findI = moment(this.queryParams.dateRange[0]).format('YYYY') + v2.split('第').join('').split('周')[0]
            }
            if (this.ishasKey(v1KesArr, findI)) {
              let i = this.ishasKey(v1KesArr, findI)
              item.push(v1[i])
            } else {
              item.push('')
            }
          }
        })
        tableData.push(item)
      })
      // console.log('tableData', tableData)
      exportJs.exportCustomerExcel(companyName, stopReason, position, tableHead, tableData, excelName, undesirableReason, countTime, sheetName)
    },
    // 判断是否存在key
    ishasKey (arr, item) {
      let flag = ''
      arr.forEach(i => {
        if (item.indexOf(String(i)) > -1) {
          flag = i
        }
      })
      return flag
    },
    getExportTableHead () {
      let tableColumns = [
        {
          label: '序号'
        },
        {
          label: '设备名称'
        },
        {
          label: '所在位置'
        },
        ...this.tableColumns
      ]
      tableColumns = tableColumns.map(item => item.label)
      return tableColumns
    },
    getDailyReport () {
      this.location.workshop = this.queryData.location.label
      this.location.reason = this.causeStopType === '1' ? this.rowParams.causeGroupName : this.rowParams.causeName
      this.location.longTime = this.rowParams.totalHaltingSeconds
      const params = {
        // pageNum: this.pagination.page,
        // pageSize: this.pagination.rowsPerPage,
        schemeLevel: this.queryData.location.level,
        deviceIds: this.queryData.devices[0] === 'all' ? [] : this.queryData.devices,
        schemeLevelId: this.queryData.location.id,
        startDate: this.queryData.dateData[0],
        endDate: this.queryData.dateData[1],
        causeId: this.causeStopType === '2' ? this.rowParams.causeId : '',
        causeGroupId:
          this.causeStopType === '1' ? this.rowParams.causeGroupId : '',
        dateType: this.queryData.dateType
      }
      this.isTableLoading = true
      this.tableColumns = this.queryData._getTableHeader
      getDailyReport(params).then(res => {
        this.isTableLoading = false
        const ret = res.data
        // 总条数
        this.pagination.rowsNumber = res.total
        // 日周月 格式
        const dateType = this.queryData.dateType
        // 原因类别还是原因查看
        // this.causeStopType
        // 日期当中区分日周月字段
        const member = {
          date: 'date',
          week: 'week',
          month: 'yearMonth'
        }
        ret.map((v, i) => {
          const item = v
          item.indexId = i + 1
          item.lineName = v.lineName === 'default' ? '--' : v.lineName
        })
        //
        this.tableData = this.getCause(ret, member[dateType])
      }).catch(() => {
        this.tableData = []
      })
    },
    // 按原因查看结果
    getCause (val, dateType) {
      const p = val
      p.map(v => {
        const item = v
        if (v.reports) {
          v.reports.map(j => {
            item[j[dateType]] = (j.haltingSeconds / 60).toFixed(2)
          })
        }
      })
      return p
    }
  },
  mounted () { }
}
</script>

<style scoped>
.w {
  width: 320px;
}
</style>
